package com.autonavi.yunda.yunji.core.vo.param;

import com.autonavi.yunda.yunji.core.enums.ParamSourceType;
import com.autonavi.yunda.yunji.core.utils.ValidUtil;
import lombok.Data;

import javax.validation.constraints.NotBlank;

import static com.autonavi.yunda.yunji.core.config.EngineConstant.GROOVY_SYNTAX_VARIABLE_REGEX;

/**
 * @author cizhong.wcs
 * @date 2022/6/1 15:48
 */
@Data
public class Param {
    @NotBlank
    public String name;
    @NotBlank
    public String type;
    public String desc;
    public ParamSourceType source = ParamSourceType.query;
    public String defaultVal;
    public boolean require = false;
    public String debugValue;
    public boolean emptyFlag;

    /**
     * 当参数名出现特殊的字符或者系统关键字时,调整参数名称
     * 比如headers中会有"Content-Type"这种参数名
     */
    public String getParamNameInScript() {
        //符合参数规范则不调整
        if (ValidUtil.checkRegexAndReturn(name, GROOVY_SYNTAX_VARIABLE_REGEX)) {
            return name;
        }
        return name.replace("-", "$");
    }

    /**
     * 根据emptyFlag对debugValue为空时从新赋值
     * 1. 当empty为true，且debugValue值为null时，改为空串
     * 2. 当empty为false，且debugValue为空串时，改为null
     */
    public void resetDebugValueBasedOnFlag() {
        if(!"string".equals(type)) {
            return;
        }

        if(this.emptyFlag && null == this.debugValue) {
            this.debugValue = "";
        }else if(!this.emptyFlag && "".equals(this.debugValue)) {
            this.debugValue = null;
        }
    }
}
